package base

import (
	"gitee.com/lsy007/mysqlclient"
	"github.com/pquerna/ffjson/ffjson"
)

func (m *MysqlHandle) ComplexExist(info *GetInfo) (bool, error) {
	// 1. 执行
	reply, err := m.SendRequest(&mysqlclient.DBInfo{
		Table: m.Table, Func: "ComplexGet", Model: m.Model, Alias: info.Alias,
		Field: info.Field, Cols: info.Cols, Omit: info.Omit,
		AutoCondition: info.AutoCondition, Where: getWhere(info.Where),
		Group: info.Group, Having: info.Having, Order: info.Order,
		Join: buildBuildCondition(info.Join),
	})
	if err != nil {
		return false, err
	}
	return reply.Has, err
}

func (m *MysqlHandle) ComplexGet(info *GetInfo) (bool, error) {
	// 1. 执行
	reply, err := m.SendRequest(&mysqlclient.DBInfo{
		Table: m.Table, Func: "ComplexGet", Model: m.Model, Alias: info.Alias,
		Field: info.Field, Cols: info.Cols, Omit: info.Omit,
		AutoCondition: info.AutoCondition, Where: getWhere(info.Where),
		Group: info.Group, Having: info.Having, Order: info.Order,
		Join: buildBuildCondition(info.Join),
	})
	if err != nil {
		return false, err
	}
	// 2. 判断是否存在值
	if !reply.Has {
		return false, err
	}
	// 3. 获取结果赋值内存
	err = ffjson.Unmarshal(reply.Model, info.Result)
	return reply.Has, err
}

func (m *MysqlHandle) ComplexFind(info *FindInfo) (has bool, err error) {
	// 1. 执行
	reply, err := m.SendRequest(&mysqlclient.DBInfo{
		Table: m.Table, Func: "ComplexFind", Model: m.Model, Alias: info.Alias,
		Field: info.Field, Cols: info.Cols,
		Join:  buildBuildCondition(info.Join),
		Where: getWhere(info.Where), Group: info.Group, Having: info.Having,
		Start: (info.Page - 1) * info.Rows, Rows: info.Rows, Order: info.Order,
	})
	if err != nil {
		return false, err
	}
	// 2. 判断是否存在值
	if !reply.Has {
		return false, nil
	}
	// 3. 获取结果赋值内存
	err = ffjson.Unmarshal(reply.Model, info.Result)
	return reply.Has, err
}
